<template>
  <div class="login">
    <!--    <div class="login-header">-->
    <!--      <span class="login-box-header-left"></span>-->
    <!--      {{ PROJECT_NAME }}-->
    <!--      <span class="login-box-header-right"></span>-->
    <!--    </div>-->
    <div class="content">
      <div class="flex">
        <div class="content-box">
          <div class="title">{{ PROJECT_NAME.slice(0, 4) }}<br>{{ PROJECT_NAME.slice(4) }}</div>
          <el-form ref="formRef" label-position="left" :model="formInline" status-icon :rules="rules"
                   :hide-required-asterisk="true">
            <el-form-item prop="username">
              <el-input placeholder="用户名" v-model="formInline.username">
<!--                <template #prefix>-->
<!--                  <el-icon>-->
<!--                    <UserFilled/>-->
<!--                  </el-icon>-->
<!--                </template>-->
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input placeholder="密码" type="password" v-model="formInline.password">
<!--                <template #prefix>-->
<!--                  <el-icon>-->
<!--                    <Lock/>-->
<!--                  </el-icon>-->
<!--                </template>-->
              </el-input>
            </el-form-item>
<!--            <el-form-item>-->
<!--              <el-checkbox v-model="autoLogin" style="font-size: 18px;color: #eaeaea;">自动登录</el-checkbox>-->
<!--            </el-form-item>-->
          </el-form>
          <div class="loginbtn">
            <el-button ref="login-submit" type="danger" @click="handleSubmit" :loading="showLogin">
              {{ showLogin ? '登录中' : '登　录' }}
            </el-button>
          </div>
        </div>
      </div>
      <div class="flex"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref, onMounted} from 'vue'
import {useRouter} from 'vue-router'
// import {userLogin} from "@/api/user";

import {StorageEnum} from '@/enums/storageEnum'
import {PageEnum} from '@/enums/pageEnum'
import {isNull} from "@/utils";

const {BASE_HOME_NAME, BASE_NAME} = PageEnum

import {
  routerTurnByName,
  cryptoEncode,
  setLocalStorage,
  clearLocalStorage,
  getLocalStorage,
  cryptoDecode
} from '@/utils'


const PROJECT_NAME = import.meta.env.DEV ? import.meta.env.VITE_GLOB_APP_TITLE : window.Z_GLOBAL_CONFIG.VITE_GLOB_APP_TITLE

const {Z_LOGIN_INFO_STORE, Z_ACCESS_TOKEN_STORE, Z_LOGIN_AUTO} = StorageEnum

const autoLogin = ref(false)
const showLogin = ref(false)

const formInline = reactive({
  username: 'admin',
  password: '123456',
})

const rules = {
  username: {
    required: true,
    message: '当前为必填项',
    trigger: 'blur',
  },
  password: {
    required: true,
    message: '当前为必填项',
    trigger: 'blur',
  },
}

const timeoutRef = ref(4000)

const router = useRouter()

const formRef = ref()

// 点击事件
const handleSubmit = (e: Event | null) => {


  showLogin.value = true
  if (e) {
    e.preventDefault()
  }
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const {username, password} = formInline

      let params = {
        username: username,
        password: password,
      }

      // 是否选择自动登录
      if (autoLogin.value) {
        setLocalStorage(
            Z_LOGIN_AUTO,
            cryptoEncode(
                JSON.stringify({
                  username,
                  password,
                })
            )
        )
      } else {
        // 否则清除曾经的自动登录记录
        clearLocalStorage(Z_LOGIN_AUTO)
      }

      // 假装登录成功
      let {code, msg, token, user} = {
        code: 200,
        msg: '成功',
        token: 'XDFSFSSDSXASDFEAF',
        user: {
          id: '123',
          username,
          password,
        }
      }

      if (Number(code) === 200) {

        setLocalStorage(
            'USERID',
            user.id
        )
        setLocalStorage(
            Z_LOGIN_INFO_STORE,
            cryptoEncode(
                JSON.stringify({
                  username,
                  password,
                })
            )
        )
        setLocalStorage(
            Z_ACCESS_TOKEN_STORE,
            token
        )
        showLogin.value = false
        ElMessage.success(msg)
        routerTurnByName('Root', true)
      } else {
        showLogin.value = false
        ElMessage.error(msg)
      }
      // userLogin(params).then(res => {
      //   let {code, msg, token, user} = res
      //   if (Number(code) === 200) {
      //
      //     setLocalStorage(
      //         'USERID',
      //         user.id
      //     )
      //     setLocalStorage(
      //         Z_LOGIN_INFO_STORE,
      //         cryptoEncode(
      //             JSON.stringify({
      //               username,
      //               password,
      //             })
      //         )
      //     )
      //     setLocalStorage(
      //         Z_ACCESS_TOKEN_STORE,
      //         token
      //     )
      //     showLogin.value = false
      //     ElMessage.success(msg)
      //     routerTurnByName(BASE_HOME_NAME, true)
      //   } else {
      //     showLogin.value = false
      //     ElMessage.error(msg)
      //   }
      //
      // })

    } else {
      showLogin.value = false
      ElMessage.error(`登录异常!`)
    }
  })
}

const loadingObj = () => {
  const openFullScreen = ElLoading.service({
    lock: true,
    text: '正在登录',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  const closeBtn = document.createElement('button');
  closeBtn.innerHTML = '关闭';
  closeBtn.className = 'closeBtn'
  closeBtn.onclick = () => {
    openFullScreen.close(); // 关闭loading
    closeAutoLogin()
    closeBtn.onclick = null; // 移除点击事件监听
    closeBtn.parentNode.removeChild(closeBtn); // 移除按钮
  };

// 将关闭按钮添加到loading遮罩上
  const mask = document.querySelector('.el-loading-mask');
  if (mask) {
    mask.appendChild(closeBtn);
  }

  return openFullScreen
}


const countdown = () => {
  // 创建关闭按钮
  if (timeoutRef.value <= 0) {
    showLogin.value = false
    loadingObj().close()
    if (cryptoDecode(getLocalStorage(Z_LOGIN_AUTO))) {
      const {username, password} = JSON.parse(cryptoDecode(getLocalStorage(Z_LOGIN_AUTO)))
      formInline.password = password
      formInline.username = username
      handleSubmit(null)
    }
  } else {
    timeoutRef.value -= 1000
    setTimeout(countdown, 1000)
  }
}

onMounted(() => {
  if (!isNull(getLocalStorage(Z_LOGIN_AUTO))) {
    loadingObj()
    autoLogin.value = true
    countdown()
    showLogin.value = true
  }
})

const closeAutoLogin = () => {
  clearLocalStorage(Z_LOGIN_AUTO)
  showLogin.value = false
  autoLogin.value = false
  loadingObj().close()
}
</script>

<style lang="scss" scoped>
@import "@/assets/var";

.login {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
  //background: $--login-bg;
  background: linear-gradient(135deg, #3c3e54 50%, #2a2c3a 50%);
  background-repeat: no-repeat;
  background-size: 100% 100%;

  &-header {
    //display: flex;
    //justify-content: space-between;
    //align-items: center;
    padding: 0 40px;
    height: 70px;
    margin-top: 128px;
    margin-bottom: 100px;
    position: relative;
    text-align: center;
    font-size: 68px;
    font-weight: bold;
    color: #91c9ff;

    &-left {
      display: inline-block;
      width: 10px;
      height: 44px;
      background-color: #91c9ff;
      margin-right: 50px;
    }

    &-right {
      display: inline-block;
      width: 10px;
      height: 44px;
      background-color: #91c9ff;
      margin-left: 50px;
    }
  }

  > .content {
    display: flex; /* 使用Flexbox让内部的.flex平均分布 */
    width: 966px; /* 宽度可以根据需求调整 */
    height: 510px;
    box-shadow: 0 15px 15px -10px rgba(0, 0, 0, 0.4), /* 底部阴影 */
    -15px 0 15px -10px rgba(0, 0, 0, 0.4), /* 左侧阴影 */
    15px 0 15px -10px #3c3e54; /* 右侧阴影 */
    //border-radius: 5px;
    //padding: 30px;
    overflow: hidden;

    .flex {
      flex: 1; /* 每个.flex盒子平均分配空间 */
      height: 100%;

      .content-box{
        width: 290px;
      }
    }

    .flex:nth-child(1) {
      display: flex;
      align-items: center;
      justify-content: center;
      background: #2e3040; /* 第一个子元素的背景颜色 */
    }

    .flex:nth-child(2) {
      background: $--login-content-bg; /* 第二个子元素的背景颜色 */
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }

    .title {
      font-size: 32px;
      font-weight: 500;
      color: #ffc870;
      text-align: center;
      height: 100px;
      line-height: 50px;
      margin-bottom: 16px;
    }

    > .el-form {
      .el-form-item {
        padding: 10px 0;

        .el-form-item__label {
          color: $color;
        }

        .el-form-item__content {
          .el-input {
            background-color: transparent;


            .el-input__wrapper {
              box-shadow: none;
              background: $--login-input-bg;
              background-size: 100%;

              &:hover {
                box-shadow: 0 0 0 1px #91c9ff;
              }
            }

            .el-input__inner {
              width: 200px;
              background: transparent;
              color: #eaeaea;
              font-size: 18px;
              height: 31px;
              line-height: 31px;
            }
          }
        }
      }
    }

    .loginbtn {
      padding-top: 10px;

      button {
        width: 100%;
      }
    }

  }
}

</style>
